package com.example.myapplication.flow

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.orhanobut.logger.Logger
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import retrofit2.Retrofit
import javax.inject.Inject

/**
 * 类描述:
 * 创建人:   tangchao$
 * 创建时间: 2021/9/10$ 8:38 PM$
 * 联系方式: 419704299@qq.com
 * 修改人:   tangchao$
 * 修改时间: 2021/9/10$ 8:38 PM$
 * 修改备注:  [说明本次修改内容]
 */
@HiltViewModel
class FlowViewModel0910 @Inject constructor(var retrofit: Retrofit) : ViewModel() {
    var value0910livedata = MutableLiveData<Any>()
    fun t1() {
        viewModelScope.launch {
            val last = productor().toList().filter {
                it > 5
            }.first()
            Logger.d("FlowViewModel0910===t1: $last");
            value0910livedata.value = last

            productor().toList().size
//                .collect {
//                //冷流同步非阻塞，生产者和消费者是交叉打印
//                Logger.d("FlowViewModel0910===t1: $it");
//
//            }

        }

    }

    suspend fun productor() = flow {
        for (i in 0..10) {
            delay(100)
            emit(i)
            Logger.d("FlowViewModel0910===emit: i" + i)
        }
    }

    fun reliu() {
        runBlocking {
            val channel = Channel<Int>()
            launch {
                for (x in 1..6) {
                    delay(100)
                    channel.send(x + 1)
                    Logger.d("FlowViewModel0910===reliu: ");

                }
                repeat(5) {
                    var re = channel.receive()
                    Logger.d("FlowViewModel0910===reliu: re" + re);

                }
                Logger.d("FlowViewModel0910===reliu: done");

            }

        }
    }
}